package org.celstec.mobilegame.gameLoaders;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import org.celstec.mobilegame.locatory.Card;
import org.jdom.Element;
import org.jdom.Namespace;

public class LoaderUtil {
	public static Namespace ns = Namespace
			.getNamespace("http://celstec.org/mobileGames");

	public static HashMap retrieveElements(Element root, String elementName) {
		HashMap hm = new HashMap();
		List<Element> list = root.getChildren(elementName, LoaderUtil.ns);
		Iterator items = list.iterator();
		while (items.hasNext()) {
			Card c = new Card((Element) items.next());
			hm.put(c.cardId, c);
		}
		return hm;
	}

	public static HashMap retrieveElementsInHashMap(Element root, String elementName,
			String className) {
		HashMap hm = new HashMap();
		try {
			List<Element> list = root.getChildren(elementName, LoaderUtil.ns);
			Iterator items = list.iterator();
			while (items.hasNext()) {
				Class aClass = Class.forName(className);
				Class parameterTypes[] = new Class[] { Element.class };
				Constructor ct = aClass.getConstructor(parameterTypes);
				Object c = ct
						.newInstance(new Object[] { (Element) items.next() });
				hm.put(c.toString(), c);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return hm;
	}
	
	public static Vector retrieveElementsInVector(Element root, String elementName,
			String className) {
		Vector v = new Vector();
		try {
			List<Element> list = root.getChildren(elementName, LoaderUtil.ns);
			Iterator items = list.iterator();
			while (items.hasNext()) {
				Class aClass = Class.forName(className);
				Class parameterTypes[] = new Class[] { Element.class };
				Constructor ct = aClass.getConstructor(parameterTypes);
				Object o = ct
						.newInstance(new Object[] { (Element) items.next() });
				v.add(o);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return v;
	}

}
